package litegame

import (
	"corelib/utils"
	"fmt"
	"net/http"
)

const (
	_baseURL               = "https://api.weixin.qq.com"
	_liteGameGetBalanceURL = "/wxa/game/getbalance"
	_liteGamePayURL        = "/wxa/game/pay"
)

type WxPayGetBalanceRet struct {
	BaseErrRet
	Balance int `json:"balance"`
}

func getWxPayBalance(helper *LiteGameHelper, openid, userip, signature string) (*WxPayGetBalanceRet, error) {
	accessToken := helper.GetAccessToken()
	data := map[string]interface{}{
		"openid":   openid,
		"offer_id": helper.mAppPayID,
		"ts":       utils.GetNowTs(),
		"zone_id":  "1",
		"env":      1,
		//"user_ip":  userip,
	}
	postBody, _ := json.Marshal(data)
	paySig := HmacSha256(helper.mAppKey, _liteGameGetBalanceURL+"&"+string(postBody))
	addr := _baseURL + _liteGameGetBalanceURL + "?access_token=%s&signature=%s&sig_method=hmac_sha256&pay_sig=%s"
	err, httpStatus, resp := httpPost(fmt.Sprintf(addr, accessToken, signature, paySig), postBody)
	if httpStatus != http.StatusOK {
		return nil, fmt.Errorf("getWxPayBalance失败 httpStatus=%d", httpStatus)
	}
	ret := &WxPayGetBalanceRet{}
	err = json.Unmarshal(resp, &ret)
	if err != nil {
		return nil, fmt.Errorf("getWxPayBalance解析失败 err=%s", err)
	}
	return ret, nil
}

type WxPayResultRet struct {
	BaseErrRet
	BillNo  string `json:"bill_no"`
	Balance int    `json:"balance"`
}

func doWxPay(helper *LiteGameHelper, openid, userip, signature string, amount int, tradeNo string) (*WxPayResultRet, error) {
	accessToken := helper.GetAccessToken()
	data := map[string]interface{}{
		"openid":   openid,
		"offer_id": helper.mAppPayID,
		"ts":       utils.GetNowTs(),
		"zone_id":  "1",
		"env":      1,
		//"user_ip":  userip,
		"amount":  amount,
		"bill_no": tradeNo,
	}
	postBody, _ := json.Marshal(data)
	paySig := HmacSha256(helper.mAppKey, _liteGamePayURL+"&"+string(postBody))
	addr := _baseURL + _liteGameGetBalanceURL + "?access_token=%s&signature=%s&sig_method=hmac_sha256&pay_sig=%s"
	err, httpStatus, resp := httpPost(fmt.Sprintf(addr, accessToken, signature, paySig), postBody)
	if httpStatus != http.StatusOK {
		return nil, fmt.Errorf("doWxPay失败 httpStatus=%d", httpStatus)
	}
	ret := &WxPayResultRet{}
	err = json.Unmarshal(resp, &ret)
	if err != nil {
		return nil, fmt.Errorf("doWxPay解析失败 err=%s", err)
	}
	return ret, nil
}
